<template>
  <div class="table">
<!--
    <el-table  @row-dblclick="onShow" v-loading="loading" :data="tableData()" style="width: 100%" class="center-table"
      @selection-change="handleSelectionChange" :cell-style="tableCellStyle"  >
-->
    <el-table ref="multipleTableRef" v-loading="loading" :data="tableData()" style="width: 100%" class="center-table"
      @selection-change="handleSelectionChange" :cell-style="tableCellStyle"   @row-dblclick="handleRowClick"  >
      <el-table-column v-if="!isCheckbox" type="selection" width="55" fixed="left" />
      <el-table-column v-if="!isSort" type="index" label="序号" width="50" fixed="left" />
      <ColumnData v-for="column of columns" :key="column.label" :item="column" />
      <el-table-column v-if="!operate" label="操作" :width="width ? width : '220'" :fixed="!fixed ? 'right' : false">
        <template #default="scope">
          <div class="operate">
            <slot :row="scope.row" name="operate" />
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="example-pagination-block">
      <el-pagination v-if="showSize"
        background
        :total="totalNum"
        @current-change="handleCurrentChange"
        :page-size="pageSize"
        @size-change="handleSizeChange" />
      <el-pagination v-else
        background
        layout="prev, pager, next ,total,sizes,jumper"
        :total="totalNum"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange" />
    </div>
  </div>
</template>

<script lang='ts'>
import { ElTable } from 'element-plus'
import { computed, defineComponent, nextTick, reactive, ref, toRefs, watch } from 'vue'
import ColumnData from './column-data.vue'
export default defineComponent({
  components: {
    ColumnData,
    ElTable,
  },
  emits: {
    modalValueChange: null,
    delectTable: null,
    typesTable: null,
    selectItem: null,
    currentChange: null,
    sizeChange:null,
    rowClick: null,
    onShow: null,
  },
  props: {
    initSelection:{
      type: Array,
      default:[] as any
    },
    tableArr: {
      type: Array,
      required: true,
    },
    pageSize:{
      type: String,
    },

    showSize: {
      type: Boolean,
    },
    width: {
      type: String,
    },
    columns: {
      type: Array,
      required: true,
    },
    pagination: {
      type: Object,
      required: true,
    },
    currentChange: {
      type: Object,
      required: true,
    },
    sizeChange: {
      type: Object,
      required: true,
    },
    operate: {
      type: Boolean,
    },
    isCheckbox: {
      type: Boolean,
    },
    total: {
      type: Number,
    },
    dataSources: {
      type: Boolean,
    },
    isSort: {
      type: Boolean,
    },
    loading: {
      type: Boolean,
    },
    fixed: {
      type: Boolean,
    },
  },
  setup(props, { emit }) {
    //表格用到的参数
    const state = reactive({
      ...props.pagination,
    })
    const multipleTableRef = ref()
    const totalNum = ref(props.total)
    const isLoading = ref(props.loading)

    const initSelect = async ()=>{
      console.log(props.initSelection,'props.initSelection');
      if (props.initSelection.length>=0){
        await nextTick()
        props.initSelection.forEach((row) => {
          multipleTableRef.value.toggleRowSelection(row, undefined)
        })
      }
    }
    watch(()=>props.initSelection,()=>{
      console.log(props.initSelection,'props.initSelection');
      props.initSelection.forEach((row) => {
        multipleTableRef.value.toggleRowSelection(row, undefined)
      })
    })
    
    initSelect()
    const multipleSelection = ref([])

    const handleSelectionChange = (val) => {
      console.log(val)
      multipleSelection.value = val
      emit('selectItem', val)
      let ids: number[] = []
      let types: number[] = []
      let selectRow: any[] = []
      if (val.length > 0) {
        val.filter(
          (item, index) => {
            selectRow.push(item)
            if (item.id) {
              ids.push(item.id)
              types.push(item.type)
              emit('delectTable', ids)
              emit('typesTable', types)
            } else if (item.userId) {
              ids.push(item.userId)
              emit('delectTable', ids)
            }

          }
        )
      } else {
        emit('delectTable', [])
      }
    }

    const onShow = (row)=>{
      // emit('rowClick',row)
      emit('onShow',row)
    }
    const handleEdit = (index: number, row) => {
      console.log(index, row)
      emit('modalValueChange', true)
    }
    const handleDelete = (index: number, row) => {
      console.log(index, row)
    }

    watch(state.total, (newValue, oldValue) => {
      console.log('值改变了', newValue)
    })

    watch(
      () => props.loading,
      (newVal) => {
        console.log(newVal, 'props.loading');
        isLoading.value = newVal
      }
    )

    watch(
      () => props.pagination.page,
      (newVal) => {
        console.log(newVal, 'props.loading');
        isLoading.value = newVal
      }
    )

    //前端限制分页（tableData为当前展示页表格）
    const tableData = () => {
      if (!props.tableArr) {
        return
      }
      totalNum.value = props.total
      // console.log(props.tableArr)
      if (props.dataSources) {
        return props.tableArr.filter(
          (item, index) => index < state.page * state.limit && index >= state.limit * (state.page - 1)
        )
      } else {
        return props.tableArr
      }

    }
    //改变页码
    const handleCurrentChange = (e) => {
      state.page = e
      emit('currentChange', e)
    }
    //改变页数限制
    const handleSizeChange = (e) => {
      state.limit = e
      emit('sizeChange', e)
    }
    const handleRowClick = (row) => {
      emit('rowClick', row)
    }

    const textColorArr = computed(() => {
      const arr: any = []
      props.columns.filter((item: any, index) => {
        if (item.textColor) {
          arr.push([item.key, index])
        }
      })
      return arr
    })

    // 改变某一列单元格字体颜色
    const tableCellStyle = ({ row, column, rowIndex, columnIndex }) => {
      let color
      textColorArr.value.filter((item, index) => {
        if (row[item[0]] == "待确认" && columnIndex - 2 == item[1]) {
          color = "color: #FFC783";
          return color;
        } else if (row[item[0]] == "已确认" && columnIndex - 2 == item[1]) {
          color = "color: #B5F1FF";
          return color;
        }
        if (row[item[0]] == "待提交" && columnIndex - 2 == item[1]) {
          color = "color: #FFC783";
          return color;
        } else if (row[item[0]] == "待审核" && columnIndex - 2 == item[1]) {
          color = "color: #B5F1FF";
          return color;
        } else if (row[item[0]] == "审批通过" && columnIndex - 2 == item[1]) {
          color = "color: #B5F1FF";
          return color;
        } else if (row[item[0]] == "驳回" && columnIndex - 2 == item[1]) {
          color = "color: #B5F1FF";
          return color;
        }
      })
      return color
    }
    return {
      totalNum,
      multipleTableRef,
      tableCellStyle,
      handleSelectionChange,
      handleEdit,
      handleDelete,
      tableData,
      onShow,
      handleCurrentChange,
      handleSizeChange,
      ...toRefs(state),
      handleRowClick,
    }
  },
})
</script>

<style lang="scss" scoped>
.center-table {
  .el-table__body-wrapper {
    overflow-x: scroll !important; // 设置横轴滚动条
  }
}

.table {
  margin-top: 15px;
}

.example-pagination-block {
  margin-top: 15px;
  text-align: center;
}

:deep(.el-pagination .btn-next .el-icon) {
  margin: 0 auto;
}

:deep(.el-pagination .btn-prev .el-icon) {
  margin: 0 auto;
}

:deep(.center-table td),
:deep(.center-table th) {
  text-align: center !important;
}
</style>
